# -*- encoding: utf-8 -*-
"""
File Name: redis_alarm_manager
Description:
Author : 'lirui'
date: 2024/2/8
Contact: marjey_lee@163.com
Change Activity:
2024/2/8:
"""
import json
from ll.third_party.redis_util.redis_client import RedisClient
from projects.monitoring.common.config.redis import REDIS_SERVER_INFO
from projects.monitoring.common.do.alarm import Alarm
from projects.monitoring.common.utils.redis_keys_util import RedisKeysUtil


class RedisAlarmManager:
    """
    load all redis alarm problems.
    """

    def __init__(
            self,
            host=REDIS_SERVER_INFO['host'],
            port=REDIS_SERVER_INFO['port']
    ):
        self.host = host
        self.port = port
        self.redis_client = self._init_client()

    def _init_client(self):
        """
        init client.
        """
        return RedisClient(host=self.host, port=self.port)

    def close(self):
        """

        Returns:

        """

    def get(self, key):
        """

        """
        return self.redis_client.get(key)

    def set(self, key, value):
        self.redis_client.insert(key, value)

    def load_current_problems(self, redis_key):
        """

        """
        res = self.redis_client.get(redis_key)
        if res is None:
            res = {}
        else:
            res = str(res, 'utf8')
            res = json.loads(res)
            new_res = {}
            for k, r in res.items():
                alarm = Alarm.json_to_obj(r)
                new_res[k] = alarm
            res = new_res
        return res

    def _load_problems(self, key):
        v = self.redis_client.get(key)
        if v is None:
            return []
        content = str(v, encoding='utf8')
        return json.loads(content)

    def get_current_warning_alarms(self):
        self.redis_client = self._init_client()
        ret = {}
        keys = RedisKeysUtil.get_all_publisher_keys()
        for k in keys:
            k = RedisKeysUtil.get_current_problem_key_by_publisher(k)
            ret[k] = self._load_problems(k)
        return ret

    def get_all_current_alarms(self):
        self.redis_client = self._init_client()
        ret = {}
        keys = RedisKeysUtil.get_all_publisher_keys()
        for k in keys:
            k = RedisKeysUtil.get_all_problem_key_by_publisher(k)
            ret[k] = self._load_problems(k)
        return ret
